package com.lw.sbdemo2.common.utils;

import com.lw.sbdemo2.common.cache.CacheHandle;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2017</p>
 * <p>公司: 智业软件</p>
 *
 * @author: linqunyuan
 * @createTime 2018/3/16
 */
public class IdUtils {

    private static String nowDayPre = DateUtils.getNowSimpleDate() + "-";

    public static boolean cacheOk = true;

    public static AtomicInteger atomicInteger = new AtomicInteger(2000000);

    public IdUtils() {
    }

    public static String uuid(boolean withLinkLine) {
        String uuidStr = UUID.randomUUID().toString();
        return withLinkLine ? uuidStr : uuidStr.replaceAll("-", "");
    }

    public static String uuid() {
        return uuid(false);
    }

    /**
     * 获取唯一订单号，日期+递增
     */
    public static synchronized String createOrderNo() {

        if (atomicInteger == null || !cacheOk) {
            return uuid();
        }

        String tempPre = DateUtils.getNowSimpleDate() + "-";
        if (!nowDayPre.equals(tempPre)) {
            nowDayPre = tempPre;
            atomicInteger.set(200000);
            CacheHandle.setOrderNum(atomicInteger);
        }
        CacheHandle.setOrderNum(new AtomicInteger(atomicInteger.incrementAndGet()));
        return tempPre + atomicInteger.incrementAndGet();
    }
}
